<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/20
 * Time: 20:42
 */
namespace Services;
use Illuminate\Http\Request;

class Route extends \AltoRouter
{
	protected $config;

	public function __construct( $routes = array(), $basePath = '', $matchTypes = array() )
	{
		$this->config = require BASE_PATH.'/config/route.php';
		parent::__construct( $this->config['routes'], $this->config['base_path'], $this->config['match_types']);
	}

	public function run()
	{
		$match = parent::match();

		if ($match)
		{
			if (is_callable($match['target']))
			{
				// call back
				call_user_func_array( $match['target'], $match['params'] );
			}else{

				list($controller, $action) = explode('@',$match['target']);
				$controller = new $controller;
				if (is_callable(array($controller,$action))){
					//call_user_func_array(array($controller, $action), $match['params']);
					call_user_func_array(array($controller, $action), array(Request::capture(),$match['params']));
				}else{
					echo 'Error: can not call ' . get_class($controller) . '@' . $action;
				}

				//$controller_method=explode('@',$match['target']);
				//$controller = new $controller_method[0]();
				//call_user_func_array(array($controller,$controller_method[1]),$match['params']);
			}
		}else{
			//echo '404 Not Found';
			throw new \Exception("路由无匹配项 404 Not Found");
		}

	}

	//	echo \Services\route::urlBuild('demoName',array('id' => 10, 'name' => 'update'));

	public static function urlBuild($routeName, array $params = array())
	{
		$route = new Route();
		return $route->generate($routeName, $params);
	}

	public static function getTplPath()
	{
		$route = new Route();
		$match = $route->match();
		$tpl_Path = str_replace("@","/",$match['target']);
		$tpl_Path = str_replace("\\","/",$tpl_Path);
		$tpl_Path = str_replace("Controllers","views",$tpl_Path);
		$tpl_Path = str_replace("Controller","",$tpl_Path);
		$tpl_Path = strtolower($tpl_Path);

		return $tpl_Path;	// smarty模板后缀 .html 放在 MySmarty文件中增加
	}

}